from celery import shared_task
from django.utils import timezone
from django.core.mail import send_mail
from borrowing.models import Borrowing
from datetime import timedelta
from django.conf import settings
import redis

redis_client = redis.Redis(host='localhost', port=6379, db=3)


@shared_task
def send_due_date_reminders():
    now = timezone.now()
    seven_days_later = now + timedelta(days=7)
    print("????", seven_days_later)
    due_soon = Borrowing.objects.filter(
        due_date__lte=seven_days_later,
        returned=False
    )
    print("/////",len(due_soon))

    # 用于存储每个用户的提醒消息列表
    user_reminders = {}
    for borrowing in due_soon:
        subject = f"【还书提醒】《{borrowing.book.title}》即将到期"
        message = (
            f"尊敬的 {borrowing.user.username}：\n"
            f"您于 {borrowing.borrow_date} 借阅的《{borrowing.book.title}》\n"
            f"将于 {borrowing.due_date} 到期，请及时归还。\n"
            "图书馆管理系统"
        )
        print(message)

        username = borrowing.user.username
        if username not in user_reminders:
            user_reminders[username] = []
        user_reminders[username].append(message)

    send_mail(
            subject=subject,
            message=message,
            from_email=settings.EMAIL_HOST_USER,
            recipient_list=[borrowing.user.email],
            fail_silently=False
        )

    # 将每个用户的提醒消息列表存入 Redis
    for username, messages in user_reminders.items():
        redis_key = f"borrowing_reminder:{username}"
        try:
            # 一次性将该用户的所有提醒消息存入 Redis 列表
            redis_client.rpush(redis_key, *messages)
            print(f"消息已存储到 Redis，键: {redis_key}")
        except redis.RedisError as e:
            print(f"存储消息到 Redis 时出错: {e}")


"""
邮件发送机制说明
角色	        是否需要验证	  验证内容	 验证目的
发送方邮箱	必须验证	SMTP 授权码/密码	确保合法发送权限
接收方邮箱	无需任何验证	无	邮件系统自动投递
"""